/* eslint-disable max-lines */
/* eslint-disable no-negated-condition */
import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Input, Modal, Message as msg} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, DATE_FORMAT, TABLE, FORM_ROW_OPTIONS, FIXED_COLUMN_WIDTH, DATETIME_FORMAT} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions, uuid, getNewData, getNowData, getUrl} from './utils';
import {getDetail, getDealersQuickly, getDealers, getShippingPorts, getCarriers, getSaleProformaInvoicesDetail, getLastTime} from './api';
import {injectIntl, language} from './intl';
import ImportPanel from './ImportPanel';
import {formatAmount, conventEnumValueToString, formatDateTime} from '../utils';
import TextInput from 'Shared/components/TextInput';
import SearchInput from 'Shared/components/SearchInput';
import styles from './style.css';
import WrappedSelect from '../common/WrappedSelect';
import Return from '../common/Return';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const {Description} = DescriptionList;
import CBUSelectPanel from './CBUSelectPanel';
import ProductPanel from './ProductPanel';
import PlanCodePanel from './PlanCodePanel';
import ProductMutiPanel from './ProductMutiPanel';
import {newOrUpdateOrderValidator} from './validator';
import FileUpload from './FileUpload';
import {saleOrderResultJudgeResult, currency, saleOrderPriceTerms,
    saleOrderTransportTypeForKd, saleOrderType, paymentType} from '../Enum';
import moment from 'moment';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import WrappedDatePicker from '../common/WrappedDatePicker';
import WrappedInputNumber from '../common/WrappedInputNumber';

const datetime = moment(new Date()).add(1, 'd').format();
const FormItem = Form.Item;
const saleOrderTransportTypeList = saleOrderTransportTypeForKd.toList(language);
const paymentTypeList = paymentType.toList(language);
const saleOrderTypeList = saleOrderType.toList(language);
const saleOrderPriceTermsList = saleOrderPriceTerms.toList(language);
let fee = 0;
class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        showCBUSelectPanel: false,
        showProductPanel: false,
        showPartOrderPlan: false,
        showPlanCodePanel: false,
        isVin: false,
        details: [],
        carrierList: [],
        shippingPortList: [],
        isAlert: true,
        isLoading: false,
        validate: false,
        isQuantity: false,
        detailId: null,
        productGroupCode: null,
        kdBomCode: null,
        saleOrderResults: [],
        tradeMethodList: [],
        newOrBatchDef: 2,
        disabledKDBOM: false,
        showProductMutiPanel: false
    }

    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok) {
                        this.setState({
                            loading: false,
                            data: res.data,
                            saleOrderResults: res.data.saleOrderResults.map(item => Object.assign(item, {id: uuid()})),
                            details: res.data.details.map(item => Object.assign(item, {
                                id: uuid(),
                                disabledInput: !item.piCode
                            })),
                            attachments: res.data.attachments
                        });
                        fee = res.data.totalAmount;
                        this.getShippingPort(res.data.brandId);
                        this.getCarrier(res.data.brandId);
                        this.getTradeMethod(res.data.brandId);
                    } else
                        this.setState(({
                            loading: false
                        }));
                });
        }
        const pi = getUrl(this.props.history.location.search);
        if(pi && pi.piId)
            getSaleProformaInvoicesDetail(pi.piId)
                .then(res => {
                    if(res.ok) {
                        const row = res.data;
                        this.getShippingPort(row.brandId);
                        this.getTradeMethod(row.brandId);
                        this.getCarrier(row.brandId);
                        if(row.saleProformaInvoiceDetails.length > 0)
                            row.saleProformaInvoiceDetails.forEach(v => {
                                fee = (v.price * v.quantity) + fee;
                            });
                        this.setState({
                            details: row.saleProformaInvoiceDetails.map(r => ({
                                id: uuid(),
                                piCode: row.code,
                                piId: row.id,
                                piDetailId: r.id,
                                productGroupCode: r.productGroupCode,
                                productGroupName: r.productGroupName,
                                descriptionOfGoods: r.descriptionOfGoods,
                                quantity: r.quantity,
                                kdBomCode: r.kdBomCode,
                                price: r.price,
                                currency: row.currency,
                                paymentType: row.paymentType,
                                salesOrderPriceTerms: row.salesOrderPriceTerms,
                                transportType: row.deliveryTerms,
                                disabledInput: false,
                                oldQuantity: r.quantity,
                                tradeMethodId: row.tradeMethodId
                            })),
                            data: Object.assign({}, this.state.data, {
                                brandId: row.brandId,
                                brandCode: row.brandCode,
                                brandName: row.brandName,
                                dealerId: row.dealerId,
                                dealerCode: row.dealerCode,
                                dealerName: row.dealerName,
                                marketDepartmentId: row.marketDepartmentId,
                                marketDepartmentName: row.marketDepartmentName,
                                country: row.country,
                                currency: row.currency,
                                tradeMethodId: row.tradeMethodId,
                                transportType: row.deliveryTerms,
                                paymentType: row.paymentType,
                                salesOrderPriceTerms: row.salesOrderPriceTerms,
                                account: row.payableAccount,
                                carrierId: row.carrierId,
                                shippingPortId: row.shippingPortId,
                                destinationPort: row.destinationPort,
                                totalAmount: row.totalAmount,
                                remark: row.remark,
                                batchNumber: row.batchNumber,
                                tradeMethodName: row.tradeMethodName,
                                orderType: saleOrderType.Normal,
                                deliveryDate: this.state.data.deliveryDate ? this.state.data.deliveryDate : datetime
                            }),
                            hasOperat: true
                        });
                    }
                });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getCBUSaleOrder = data => {
        if(data.dealerId && data.brandId && data.transportType && data.orderType) {
            this.setState({loading: true});
            getLastTime({
                dealerId: data.dealerId,
                brandId: data.brandId,
                transportType: data.transportType,
                orderType: data.orderType,
            })
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: Object.assign({}, data, {
                                salesOrderPriceTerms: res.data.salesOrderPriceTerms,
                                paymentType: res.data.paymentType,
                                carierId: res.data.carierId,
                                carrierName: res.data.carrierName,
                                destinationPort: res.data.destinationPort
                            })
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
    }
    // eslint-disable-next-line react/sort-comp
    onChange = (value, name) => {
        if(name === 'vinYear')
            this.setState({isVin: true});
        
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
        if(this.state.tradeMethodList.length === 0)
            this.getTradeMethod(this.state.data.brandId);
        if(this.props.initEnum.brands && this.props.initEnum.brands.length === 1 && this.state.shippingPortList.length === 0) {
            this.getShippingPort(this.props.initEnum.brands[0].value);
            this.getCarrier(this.props.initEnum.brands[0].value);
        }
    }
    onChangeSwitchBrand = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value,
            brandCode: this.props.initEnum.brands.find(v => v.value === value).text,
            dealerId: '',
            dealerCode: '',
            dealerName: '',
            country: '',
            currency: undefined
        });
        this.setState({
            data,
            details: [],
            hasOperat: true
        });
    }
    getShippingPort = id => {
        getShippingPorts({brandId: id}).then(res => {
            if(res.ok)
                this.setState({
                    shippingPortList: res.data.content.map(item => ({
                        text: `${'('}${item.code}${')'}${item.name}`,
                        value: item.id
                    }))
                });
        });
    }
    getCarrier = id => {
        getCarriers({brandId: id}).then(res => {
            if(res.ok)
                this.setState({
                    carrierList: res.data.content.map(item => ({
                        text: `${'('}${item.code}${')'}${item.name}`,
                        value: item.id
                    }))
                });
        });
    }
    getTradeMethod = id => {
        getDealers({brandId: id}).then(res => {
            const obj = {};
            if(res.ok) {
                const tradeMethodList = res.data.content.map(item => ({
                    text: item.tradeMethodName,
                    value: item.tradeMethodId
                })).reduce((cur, next) => {
                    // eslint-disable-next-line no-unused-expressions
                    obj[next.value] ? '' : obj[next.value] = true && cur.push(next);
                    return cur;
                }, []);
                this.setState({
                    tradeMethodList
                });
            }
        });
    }
    onChangeBrand = (value, name) => {
        this.getCarrier(value);
        this.getShippingPort(value);
        this.getTradeMethod(value);

        if(this.state.details.length > 0 && this.state.data.brandId !== null && this.state.data.brandId !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch',
                    defaultMessage: '变更品牌，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitchBrand(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value,
                    brandCode: this.props.initEnum.brands.find(v => v.value === value).text
                }),
                hasOperat: true
            });
    }
    isNull = arg1 => Boolean(!arg1 && arg1 !== 0 && typeof arg1 !== 'boolean')
    onSelectCBU = records => {
        let retailDetails = this.state.details || [];
        records.forEach(r => {
            const index = retailDetails.findIndex(v => v.piDetailId === r.id);
            if(index === -1)
                retailDetails.push({
                    id: uuid(),
                    piCode: r.piCode,
                    piId: r.piId,
                    piDetailId: r.id,
                    descriptionOfGoods: r.descriptionOfGoods,
                    piSubmitTime: r.piSubmitTime,
                    kdBomCode: r.kdBomCode,
                    quantity: r.quantity,
                    oldQuantity: r.quantity,
                    price: r.price,
                    currency: r.currency,
                    paymentType: r.paymentType,
                    salesOrderPriceTerms: r.salesOrderPriceTerms,
                    transportType: r.transportType,
                });
        });
        retailDetails = retailDetails.filter(d => d.piId);
        this.setState({
            data: Object.assign({}, this.state.data, {
                currency: records[0].currency,
                paymentType: records[0].paymentType,
                salesOrderPriceTerms: records[0].salesOrderPriceTerms,
                transportType: records[0].transportType,
                tradeMethodId: records[0].tradeMethodId,
            }),
            details: [...retailDetails],
            hasOperat: true,
            showCBUSelectPanel: false,
            isAlert: true
        });
    }
    onSelectProduct = data => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === this.state.detailId)
                return Object.assign({}, d, {
                    productId: data.id,
                    productCategoryId: data.modelId,
                    productCategoryCode: data.modelCode,
                    productCategoryName: data.modelName,
                    engineModel: data.engineModelName,
                    transmission: data.transmission,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true,
            showProductPanel: false,
        });
    }
    onSelectPlanCode = data => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === this.state.detailId)
                return Object.assign({}, d, {
                    planCodeId: data.id,
                    planCode: data.planCode,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true,
            showPlanCodePanel: false,
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const time = new Date();
        const {data, details, isVin} = this.state;
        if(!data.vinYear && !isVin)
            data.vinYear = time.getFullYear();
        
        const isValid = newOrUpdateOrderValidator(data, details);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        if(this.props.page === 'force')
            this.props.onSubmitForce(data, details).then(res => {
                if(res.success)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
        else
            this.props.onSubmit(data, details).then(res => {
                if(res.success)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    onSelectDealer = dealer => {
        // this.getCBUSaleOrder({
        //     ...this.state.data,
        //     dealerId: dealer.id
        // });
        this.setState({
            details: []
        });
        this.setState({
            data: Object.assign({}, this.state.data, {
                dealerId: dealer.id,
                dealerCode: dealer.code,
                dealerName: dealer.name,
                country: dealer.countryName,
                currency: dealer.currency,
                tradeMethodName: dealer.tradeMethodName,
                tradeMethodId: dealer.tradeMethodId,
                marketDepartmentId: dealer.marketDepartmentId,
                marketDepartmentName: dealer.marketDepartmentName,
                orderType: dealer.orderType,
                transportType: dealer.transportType,
                paymentType: dealer.paymentType,
                salesOrderPriceTerms: dealer.salesOrderPriceTerms,
                account: dealer.account,
                batchNumber: dealer.batchNumber,
                carrierName: dealer.carrierName,
                carrierId: dealer.carrierId,
                shippingPortId: dealer.shippingPortId,
                shippingPortName: dealer.shippingPortName,
                destinationPort: dealer.destinationPort,
                deliveryDate: getNewData(getNowData(), dealer.deliveryDate)
            })
        });
        if(this.state.tradeMethodList.length === 0)
            this.getTradeMethod(this.state.data.brandId);
        if(this.props.initEnum.brands && this.props.initEnum.brands.length === 1 && this.state.shippingPortList.length === 0) {
            this.getShippingPort(this.props.initEnum.brands[0].value);
            this.getCarrier(this.props.initEnum.brands[0].value);
        }
    }
    onChangeOrderPriceTerms = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value,
            account: null,
            carrierId: null,
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onCloseCBUSelectPanel = () => {
        this.setState({showCBUSelectPanel: false});
    }
    onCloseProductPanel = () => {
        this.setState({showProductPanel: false});
    }
    onClosePlanCodePanel = () => {
        this.setState({showPlanCodePanel: false});
    }
    onClickCBU = () => {
        if(!this.state.data.brandId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.brandId',
                defaultMessage: '请先选择品牌'
            }));
        if(!this.state.data.dealerId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.dealerId',
                defaultMessage: '请先选择总代'
            }));
        this.setState({showCBUSelectPanel: true});
    }
    onClickProduct = (id, piCode) => {
        // if(this.isNull(piCode))
        //     return msg.warn(this.props.intl.formatMessage({
        //         id: 'newPanel.message.requiredIcon',
        //         defaultMessage: '请先选择PI编号'
        //     }));
        this.setState({showProductPanel: true,
            detailId: id});
    }
    onClickPlanCode = (id, kdBomCode) => {
        if(this.isNull(kdBomCode))
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.requiredKdBomCode',
                defaultMessage: '请先填写KdBom编号'
            }));
            
        this.setState({
            kdBomCode,
            showPlanCodePanel: true,
            detailId: id,
        });
    }
    onClickAddDetailBtn = () => {
        const details = this.state.details;
        this.setState({
            details: [
                ...details,
                {
                    id: uuid(),
                    piCode: ''
                }
            ],
            hasOperat: true
        });
    };
    onTableChange = (value, name, id, piCode) => {
        const details = this.state.details || [];

        // if(name === 'kdBomCode' && this.isNull(piCode))
        //     this.setState({
        //         disabledInput: true
        //     });
        // if(name === 'kdBomCode' && this.isNull(value))
        //     this.setState({
        //         disabledInput: false
        //     });
        
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    validatePrice = (value, kdBomCode, id) => {
        const details = this.state.details || [];
        details.map(d => {
            if(d.kdBomCode === kdBomCode)
                if(d.price !== value) {
                    this.onTableChange('', 'price', id);
                    return msg.warn(this.props.intl.formatMessage({
                        id: 'newPanel.message.validatePrice',
                        defaultMessage: '相同KDBOM号的单价不同'
                    }));
                }
            return d;
        });
    }
    onDelete = e => {
        const addedItemId = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.id !== addedItemId);
        this.setState({
            details: [...tmp],
            hasOperat: true
        });
        if(this.state.details.length === 1)
            this.setState({
                productGroupCode: null,
                disabledKDBOM: false,
            });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true,
            disabledKDBOM: false,
            productGroupCode: null,
        });
    }
    onClickImportBtn = () => {
        if(!this.state.data.brandId || !this.state.data.dealerId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.brandIdandDealerId',
                defaultMessage: '请先选择品牌和总代'
            }));
        this.setState({showImportPanel: true});
    }
    onImportChange = records => {
        if(records.payload) {
            const {details} = this.state;
            let retailDetails = details;
            records.payload.content.forEach(r => {
                const index = retailDetails.findIndex(v => v.kdBomCode && v.kdBomCode === r.kdBomCode);

                if(index === -1)
                    retailDetails.push({
                        id: r.id,
                        kdBomCode: r.kdBomCode,
                        kdBomVersionCode: r.kdBomVersionCode,
                        descriptionOfGoods: r.descriptionOfGoods,
                        quantity: r.quantity,
                        price: r.price,
                        totalPrice: (r.quantity * r.price) || 0,
                        containerNumber: r.containerNumber,
                        batchNumber: r.batchNumber,
                        materialGroupCode: r.materialGroupCode,
                        productCategoryCode: r.productCategoryCode,
                        productCategoryName: r.productCategoryName,
                        productCategoryId: r.productCategoryId,
                        engineModel: r.engineModel,
                        transmission: r.transmission,
                        disabledInput: true
                    });
                else
                    retailDetails.splice(index, 1, {
                        id: r.id,
                        kdBomCode: r.kdBomCode,
                        kdBomVersionCode: r.kdBomVersionCode,
                        descriptionOfGoods: r.descriptionOfGoods,
                        quantity: r.quantity,
                        price: r.price,
                        totalPrice: (r.quantity * r.price) || 0,
                        containerNumber: r.containerNumber,
                        batchNumber: r.batchNumber,
                        materialGroupCode: r.materialGroupCode,
                        productCategoryCode: r.productCategoryCode,
                        productCategoryName: r.productCategoryName,
                        productCategoryId: r.productCategoryId,
                        engineModel: r.engineModel,
                        transmission: r.transmission,
                        disabledInput: true
                    });
            });
            retailDetails = retailDetails.filter(d => d.kdBomCode);
            this.setState({
                details: [...retailDetails],
                hasOperat: true,
                showImportPanel: false,
                loading: false
            });
        }
    }
    onCloseImportPanel = () => {
        this.setState({showImportPanel: false});
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onChangeCurrency = (value, name) => {
        if(this.state.details.length > 0 && this.state.data.currency !== null && this.state.data.currency !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch.currency',
                    defaultMessage: '变更币种，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitchOther(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value
                }),
                hasOperat: true
            });
        if(this.state.tradeMethodList.length === 0)
            this.getTradeMethod(this.state.data.brandId);
        if(this.props.initEnum.brands && this.props.initEnum.brands.length === 1 && this.state.shippingPortList.length === 0) {
            this.getShippingPort(this.props.initEnum.brands[0].value);
            this.getCarrier(this.props.initEnum.brands[0].value);
        }
    }
    onChangePaymentType = (value, name) => {
        if(this.state.details.length > 0 && this.state.data.paymentType !== null && this.state.data.paymentType !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch.paymentType',
                    defaultMessage: '变更付款方式，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitchOther(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value
                }),
                hasOperat: true
            });
        if(this.state.tradeMethodList.length === 0)
            this.getTradeMethod(this.state.data.brandId);
        if(this.props.initEnum.brands && this.props.initEnum.brands.length === 1 && this.state.shippingPortList.length === 0) {
            this.getShippingPort(this.props.initEnum.brands[0].value);
            this.getCarrier(this.props.initEnum.brands[0].value);
        }
    }
    onChangeOrderPriceTerms = (value, name) => {
        if(this.state.details.length > 0 && this.state.data.salesOrderPriceTerms !== null && this.state.data.salesOrderPriceTerms !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch.salesOrderPriceTerms',
                    defaultMessage: '变更价格条款，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitchOther(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value,
                    account: null,
                    carrierId: null,
                }),
                hasOperat: true
            });
        if(this.state.tradeMethodList.length === 0)
            this.getTradeMethod(this.state.data.brandId);
        if(this.props.initEnum.brands && this.props.initEnum.brands.length === 1 && this.state.shippingPortList.length === 0) {
            this.getShippingPort(this.props.initEnum.brands[0].value);
            this.getCarrier(this.props.initEnum.brands[0].value);
        }
    }
    onChangeTransportType = (value, name) => {
        if(this.state.details.length > 0 && this.state.data.transportType !== null && this.state.data.transportType !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch.transportType',
                    defaultMessage: '变更运输方式，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitchOther(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value
                }),
                hasOperat: true
            });
        if(this.state.tradeMethodList.length === 0)
            this.getTradeMethod(this.state.data.brandId);
        if(this.props.initEnum.brands && this.props.initEnum.brands.length === 1 && this.state.shippingPortList.length === 0) {
            this.getShippingPort(this.props.initEnum.brands[0].value);
            this.getCarrier(this.props.initEnum.brands[0].value);
        }
    }
    onChangeSwitchOther = (value, name) => {
        if(name === 'salesOrderPriceTerms') {
            const data = Object.assign({}, this.state.data, {
                [name]: value,
                account: null,
                carrierId: null,
            });
            this.setState({
                data,
                details: [],
                hasOperat: true
            });
        } else {
            const data = Object.assign({}, this.state.data, {
                [name]: value,
            });
            this.setState({
                data,
                details: [],
                hasOperat: true
            });
        }
    }
    onClickProductBtn = () => {
        if(!this.state.data.brandId || !this.state.data.dealerId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.brandIdandDealerId',
                defaultMessage: '请先选择品牌和总代'
            }));
        this.setState({showProductMutiPanel: true});
    }
    onSelectProductMuti = data => {
        const retailDetails = this.state.details || [];
        data.forEach(r => {
            const index = retailDetails.findIndex(v => v.productId === r.id && !v.piId);
            if(index === -1)
                retailDetails.push({
                    id: uuid(),
                    productId: data.id,
                    productCategoryId: data.modelId,
                    productCategoryCode: data.modelCode,
                    productCategoryName: data.modelName,
                    engineModel: data.engineModelName,
                    transmission: data.transmission,
                    disabledInput: false
                });
        });
        this.setState({
            details: [...retailDetails],
            hasOperat: true,
            showProductMutiPanel: false
        });
    }
    onCloseProductMutiPanel = () => {
        this.setState({showProductMutiPanel: false});
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, carrierList, loading, shippingPortList, tradeMethodList} = this.state;
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        let fee1 = 0;
        if(details.length > 0)
            details.forEach(v => {
                fee1 = ((v.price || 0) * (v.quantity || 0)) + fee1;
            });
        let totalProductCategory = 0;
        const totalProductCategoryArr = [];
        let totalProductCategoryNum = 0;
        details.forEach(o => {
            if(o.productCategoryCode)
                if(totalProductCategoryArr.length === 0)
                    totalProductCategoryArr.push({
                        productCategoryCode: o.productCategoryCode
                    });
                else {
                    const index = totalProductCategoryArr.findIndex(v => v.productCategoryCode === o.productCategoryCode);
                    if(index === -1)
                        totalProductCategoryArr.push({
                            productCategoryCode: o.productCategoryCode
                        });
                }
            
            totalProductCategory = totalProductCategoryArr.length;
            totalProductCategoryNum += o.quantity;
        });
        const validateOrderType = !data.orderType && this.state.validate ? 'error' : null;
        const validateTransportType = !data.transportType && this.state.validate ? 'error' : null;
        const validatePaymentType = !data.paymentType && this.state.validate ? 'error' : null;
        const validateSalesOrderPriceTerms = !data.salesOrderPriceTerms && this.state.validate ? 'error' : null;
        const validateAccount = !data.account && this.state.validate ? 'error' : null;
        const validateShippingPort = !data.shippingPortId && this.state.validate ? 'error' : null;
        const validateDestinationPort = !data.destinationPort && this.state.validate ? 'error' : null;
        const validateBrandId = !data.brandId && this.state.validate ? 'error' : null;
        const validateDealer = !data.dealerId && this.state.validate ? 'error' : null;
        const validateCarier = !data.carrierId && this.state.validate ? 'error' : null;
        const validateRemark = data.remark && data.remark.length > 100 && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.add, this.props.permissions) || !hasPermissions(PERMISSION.update, this.props.permissions) ||
        !hasPermissions(PERMISSION.assistAdd, this.props.permissions) || !hasPermissions(PERMISSION.assistUpdate, this.props.permissions);
        if(this.props.initEnum.brands.length === 1 && !this.props.id) {
            data.brandId = this.props.initEnum.brands[0].value;
            data.brandCode = this.props.initEnum.brands[0].text;
        }
        const time = new Date();
        const queryCondition = {
            brandId: data.brandId
        };
        const dealerComp = data.brandId ? (<DealerSelectPanel
            allowClear={false}
            value={dealerInfo}
            getDealerSimple={getDealersQuickly}
            getDealers={getDealers}
            conditions={queryCondition}
            onSelect={this.onSelectDealer} />) : (<TextInput name="dealerId"
            value={''} disabled={true} placeholder={this.props.intl.formatMessage({
                id: 'newPanel.dealerComp.placeholder',
                defaultMessage: '请先选择品牌'
            })} />);
        const approveColums = [{
            title: formatMessage({
                id: 'newPanel.column.approveSequence',
                defaultMessage: '审核序号'
            }),
            dataIndex: 'approveSequence',
            width: 120,
        }, {
            title: formatMessage({
                id: 'newPanel.column.approverCode',
                defaultMessage: '审核人编号'
            }),
            dataIndex: 'approverCode',
            width: 120,
        }, {
            title: formatMessage({
                id: 'newPanel.column.approverName',
                defaultMessage: '审核人姓名'
            }),
            dataIndex: 'approverName',
            width: 120,
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            width: 120,
            render: text => formatDateTime(text, 'YYYY-MM-DD h:mm:ss')
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveComment',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approveComment',
            width: 300,
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveResult',
                defaultMessage: '判定结果'
            }),
            dataIndex: 'approveResult',
            width: 300,
            render: text => conventEnumValueToString(saleOrderResultJudgeResult, text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.nextOperation',
                defaultMessage: '下一步操作'
            }),
            dataIndex: 'nextOperation',
            width: 300,
        }];
        const colums = [{
            title: formatMessage({
                id: 'newPanel.column.piCode',
                defaultMessage: 'PI编号'
            }),
            dataIndex: 'piCode'
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.column.kdBomCode',
                defaultMessage: 'KDBOM号'
            })}</span>,
            dataIndex: 'kdBomCode',
            width: 200,
            render: (text, record) => {
                const validate = (!text) && this.state.validate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <TextInput
                            disabled={this.state.disabledKDBOM || !this.isNull(record.piCode)}
                            name="kdBomCode"
                            value={record.kdBomCode}
                            onChange={value => this.onTableChange(value, 'kdBomCode', record.id, record.piCode)} />
                    </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.kdBomVersionCode',
                defaultMessage: 'KDBOM版本号'
            }),
            dataIndex: 'kdBomVersionCode',
            width: 200,
            render: (text, record) => (
                <FormItem>
                    <TextInput
                        name="kdBomVersionCode"
                        value={record.kdBomVersionCode}
                        onChange={value => this.onTableChange(value, 'kdBomVersionCode', record.id)} />
                </FormItem>
            )
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.column.quantity',
                defaultMessage: '数量'
            })}</span>,
            dataIndex: 'quantity',
            width: 100,
            render: (text, record) => {
                const validate = (!text) && this.state.validate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedInputNumber
                            // disabled={!this.isNull(record.piCode) && !this.isNull(record.quantity)}
                            name="quantity"
                            min={0}
                            max={!this.isNull(record.piCode) ? record.oldQuantity : 100000000}
                            precision={0}
                            value={record.quantity}
                            onChange={value => this.onTableChange(value, 'quantity', record.id)} />
                    </FormItem>
                );
            }
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            })}</span>,
            dataIndex: 'price',
            width: 100,
            render: (text, record) => {
                const validate = (!text) && this.state.validate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedInputNumber
                            name="price"
                            min={0}
                            precision={2}
                            value={record.price}
                            onBlur={value => this.validatePrice(value, record.kdBomCode, record.id)}
                            onChange={value => this.onTableChange(value, 'price', record.id)} />
                    </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.oldQuantity',
                defaultMessage: '可用数量'
            }),
            dataIndex: 'oldQuantity',
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.column.totalPrice',
                defaultMessage: '总价'
            })}</span>,
            dataIndex: 'totalPrice',
            width: 100,
            render: (text, record) => {
                const validate = (!text) && this.state.validate ? {validateStatus: 'error'} : null;
                record.totalPrice = record.price * record.quantity || 0;
                return (
                    <FormItem {...validate}>
                        <WrappedInputNumber
                            disabled={true}
                            name="totalPrice"
                            precision={2}
                            value={record.totalPrice}
                            onChange={value => this.onTableChange(value, 'totalPrice', record.id)} />
                    </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.containerNumber',
                defaultMessage: '集装箱数'
            }),
            dataIndex: 'containerNumber',
            width: 100,
            render: (text, record) => (
                <FormItem>
                    <WrappedInputNumber
                        name="containerNumber"
                        min={0}
                        precision={0}
                        value={record.containerNumber}
                        onChange={value => this.onTableChange(value, 'containerNumber', record.id)} />
                </FormItem>
            )
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.column.batchNumber',
                defaultMessage: '批次号'
            })}</span>,
            dataIndex: 'batchNumber',
            width: 200,
            render: (text, record) => (
                <FormItem>
                    <TextInput
                        name="batchNumber"
                        value={record.batchNumber}
                        onChange={value => this.onTableChange(value, 'batchNumber', record.id)} />
                </FormItem>
            )
        }, {
            title: formatMessage({
                id: 'newPanel.column.descriptionOfGoods',
                defaultMessage: '产品描述'
            }),
            dataIndex: 'descriptionOfGoods',
            width: 200,
            render: (text, record) => (
                <FormItem>
                    <TextInput
                        name="descriptionOfGoods"
                        value={record.descriptionOfGoods}
                        onChange={value => this.onTableChange(value, 'descriptionOfGoods', record.id)} />
                </FormItem>
            )
        },
        // {
        //     title: formatMessage({
        //         id: 'newPanel.column.planCode',
        //         defaultMessage: '滚动计划编号'
        //     }),
        //     dataIndex: 'planCode',
        //     width: 200,
        //     render: (text, record) => {
        //         const validate = (!text) && this.state.validate ? {validateStatus: 'error'} : null;
        //         return (
        //             <FormItem {...validate}>
        //                 <SearchInput
        //                     value={record.planCode}
        //                     id={record.id}
        //                     onClickSearchBtn={() => this.onClickPlanCode(record.id, record.kdBomCode)} />
        //             </FormItem>
        //         );
        //     }
        // },
        {
            title: formatMessage({
                id: 'newPanel.column.productCategoryCode',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'productCategoryCode',
            width: 150,
            render: (text, record) => (
                <FormItem>
                    <SearchInput
                        value={record.productCategoryCode}
                        id={record.id}
                        onClickSearchBtn={() => this.onClickProduct(record.id, record.piCode)} />
                </FormItem>
            )
        }, {
            title: formatMessage({
                id: 'newPanel.column.piSubmitTime',
                defaultMessage: '提报时间'
            }),
            dataIndex: 'piSubmitTime',
            width: 120,
            render: text => formatDateTime(text, DATE_FORMAT)
        },
        {
            title: formatMessage({
                id: 'newPanel.column.productCategoryName',
                defaultMessage: '车型名称'
            }),
            dataIndex: 'productCategoryName',
            width: 100,
        }, {
            title: formatMessage({
                id: 'newPanel.column.engineModel',
                defaultMessage: '发动机型号'
            }),
            dataIndex: 'engineModel',
            width: 100,
        }, {
            title: formatMessage({
                id: 'newPanel.column.transmission',
                defaultMessage: '手自动'
            }),
            dataIndex: 'transmission',
            width: 100,
        }, {
            title: details.length ? (
                <WrappedPopconfirm
                    id="delete"
                    title={this.props.intl.formatMessage({
                        id: 'newPanel.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'newPanel.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'newPanel.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.onDeleteAll}>
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'newPanel.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                </WrappedPopconfirm>
            ) : (
                <a>
                    {this.props.intl.formatMessage({
                        id: 'newPanel.deleteAll',
                        defaultMessage: '清空'
                    })}
                </a>
            ),
            dataIndex: 'action',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: (text, record) => <a onClick={this.onDelete} key="delete" data-id={record.id}>
                {this.props.intl.formatMessage({
                    id: 'newPanel.delete',
                    defaultMessage: '删除'
                })}
            </a>
        }];
            
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'newPanel.column.common',
                        defaultMessage: '基础信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '订单编号'
                                    })}
                                    {...FORM_OPTIONS.item} >
                                        <Input placeholder={formatMessage({
                                            id: 'newPanel.operation.notGenerate',
                                            defaultMessage: '尚未生成'
                                        })} value={data.code} disabled />
                                    </FormItem>
                                </Col>
                                {
                                    this.props.initEnum.brands.length !== 1 &&
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'newPanel.operation.brandId',
                                                defaultMessage: '品牌'
                                            })}
                                            {...FORM_OPTIONS.item}
                                            validateStatus={validateBrandId}
                                            required>
                                            <WrappedSelect
                                                name="brandId"
                                                options={this.props.initEnum.brands}
                                                value={data.brandId}
                                                onChange={this.onChangeBrand} />
                                        </FormItem>
                                    </Col>
                                }
                                {!this.props.id ? <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateDealer}
                                        required>
                                        {dealerComp}
                                    </FormItem>
                                </Col> : <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'newPanel.form.dealerId',
                                        defaultMessage: '总代'
                                    })}{...FORM_OPTIONS.item}>
                                        {!data.dealerCode ? '' : `(${data.dealerCode})${data.dealerName}`}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.country',
                                        defaultMessage: '国家'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item} required>
                                        {
                                            this.props.id ? conventEnumValueToString(currency, data.currency) : <WrappedSelect
                                                allowClear
                                                name="currency"
                                                value={data.currency}
                                                options={currency.toList(language)}
                                                onChange={this.onChangeCurrency}/>
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.tradeMethodId',
                                        defaultMessage: '贸易方式'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            allowClear
                                            name="tradeMethodId"
                                            value={data.tradeMethodId}
                                            options={tradeMethodList}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.marketDepartmentId',
                                        defaultMessage: '大区'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.marketDepartmentName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.salesOrderPriceTerms',
                                            defaultMessage: '价格条款'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateSalesOrderPriceTerms}
                                        required>
                                        <WrappedSelect
                                            allowClear
                                            name="salesOrderPriceTerms"
                                            value={data.salesOrderPriceTerms}
                                            options={saleOrderPriceTermsList}
                                            onChange={this.onChangeOrderPriceTerms} />
                                    </FormItem>
                                </Col>

                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.orderType',
                                            defaultMessage: '订单类型'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateOrderType}
                                        required>
                                        <WrappedSelect
                                            name="orderType"
                                            value={data.orderType}
                                            options={saleOrderTypeList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.transportType',
                                            defaultMessage: '运输方式'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateTransportType}
                                        required>
                                        <WrappedSelect
                                            name="transportType"
                                            value={data.transportType}
                                            options={saleOrderTransportTypeList}
                                            onChange={this.onChangeTransportType} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.paymentType',
                                            defaultMessage: '付款方式'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validatePaymentType}
                                        required>
                                        <WrappedSelect
                                            allowClear
                                            name="paymentType"
                                            value={data.paymentType}
                                            options={paymentTypeList}
                                            onChange={this.onChangePaymentType} />
                                    </FormItem>
                                </Col>
                                {
                                    data.salesOrderPriceTerms === saleOrderPriceTerms.FCA &&
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'newPanel.operation.account',
                                            defaultMessage: '到付账号'
                                        })} {...FORM_OPTIONS.item}
                                        validateStatus={data.salesOrderPriceTerms === saleOrderPriceTerms.FCA ? validateAccount : null}
                                        required={data.salesOrderPriceTerms === saleOrderPriceTerms.FCA}>
                                            <TextInput
                                                name="account"
                                                value={data.account}
                                                onBlur={this.onChange} />
                                        </FormItem>
                                    </Col>
                                }
                                {
                                    (data.salesOrderPriceTerms === saleOrderPriceTerms.FCA ||
                                        data.salesOrderPriceTerms === saleOrderPriceTerms.FOB ||
                                        data.salesOrderPriceTerms === saleOrderPriceTerms.EXW) &&
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'newPanel.operation.carrierId',
                                            defaultMessage: '指定货代'
                                        })} {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                name="carrierId"
                                                options={carrierList}
                                                value={data.carrierId}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                }
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.shippingPortId',
                                        defaultMessage: '发运港口'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateShippingPort}
                                    required>
                                        <WrappedSelect
                                            name="shippingPortId"
                                            options={shippingPortList}
                                            value={data.shippingPortId}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.destinationPort',
                                        defaultMessage: '目的港口'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateDestinationPort}
                                    required>
                                        <TextInput
                                            name="destinationPort"
                                            value={data.destinationPort}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.vinYear',
                                        defaultMessage: 'VIN码年份'
                                    })} {...FORM_OPTIONS.item} >
                                        <WrappedInputNumber
                                            min={0}
                                            precision={0}
                                            name="vinYear"
                                            value={data.vinYear || time.getFullYear()}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.deliveryDate',
                                        defaultMessage: '需求交期'
                                    })} {...FORM_OPTIONS.item} required>
                                        <WrappedDatePicker
                                            name="deliveryDate"
                                            value={data.deliveryDate}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.planBargeShippingTime',
                                        defaultMessage: '计划驳船发运时间'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedDatePicker
                                            name="planBargeShippingTime"
                                            value={data.planBargeShippingTime}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.batchNumber',
                                        defaultMessage: '批次号'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="batchNumber"
                                            value={data.batchNumber}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.totalAmount',
                                        defaultMessage: '总金额'
                                    })} {...FORM_OPTIONS.item} required>
                                        {formatAmount(fee1)}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item} validateStatus={validateRemark}>
                                        <TextInput
                                            type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card title={formatMessage({
                        id: 'newPanel.operation.detail',
                        defaultMessage: '整车销售订单清单'
                    })}
                    extra={<div>
                        <Button
                            size="small"
                            disabled={!(details.length === 0 || (details.length > 0 && details.some(v => Boolean(v.piCode))))}
                            onClick={this.onClickCBU}>
                            {formatMessage({
                                id: 'newPanel.operation.pi',
                                defaultMessage: '根据PI新增清单'
                            })}
                        </Button>
                        <Button
                            size="small"
                            disabled={!(details.length === 0 || (details.length > 0 && details.some(v => !v.piCode)))}
                            onClick={this.onClickImportBtn}>
                            {formatMessage({
                                id: 'newPanel.operation.import',
                                defaultMessage: '导入清单'
                            })}
                        </Button>
                    </div>}>
                        {
                            <Button
                                type="dashed"
                                icon="plus"
                                block
                                disabled={!(details.length === 0 || (details.length > 0 && details.some(v => !v.piCode)))}
                                className={styles.plusBtn}
                                onClick={this.onClickAddDetailBtn}>
                                {formatMessage({
                                    id: 'newPanel.operation.new',
                                    defaultMessage: '手工新增'
                                })}
                            </Button>
                        }
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            footer={() => (<DescriptionList>
                                <Description term={formatMessage({
                                    id: 'newPanel.operation.totalProductCategory',
                                    defaultMessage: '车型汇总'
                                })}>{totalProductCategory ? totalProductCategory : null}
                                </Description>
                                <Description term={formatMessage({
                                    id: 'newPanel.operation.totalProductCategoryNum',
                                    defaultMessage: '车型数量汇总'
                                })}>{totalProductCategoryNum ? totalProductCategoryNum : null}
                                </Description>
                                <Description term={formatMessage({
                                    id: 'newPanel.operation.fee',
                                    defaultMessage: '金额汇总显示'
                                })}>{formatAmount(fee1 ? fee1 : null)}
                                </Description>
                            </DescriptionList>)}
                            {...TABLE} />
                    </Card>
                    {
                        this.props.id ? <Card title={formatMessage({
                            id: 'newPanel.operation.saleOrderResults',
                            defaultMessage: '审核结构清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={approveColums}
                                rowKey="id"
                                pagination={false}
                                dataSource={this.state.saleOrderResults}
                                {...TABLE} />
                        </Card> : null
                    }
                    <Card title={this.props.intl.formatMessage({
                        id: 'newPanel.title.files',
                        defaultMessage: '附件清单'
                    })}>
                        <Row>
                            <FileUpload onChange={this.onChangeUpload}
                                onRemove={this.removeFilePath}
                                fileList={data.attachments || []}/>
                        </Row>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSave',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showCBUSelectPanel &&
                        <CBUSelectPanel
                            currentSelectRowkeys={details}
                            paymentType={data.paymentType}
                            salesOrderPriceTerms={data.salesOrderPriceTerms}
                            transportType={data.transportType}
                            tradeMethodId={data.tradeMethodId}
                            tradeMethodName={data.tradeMethodName}
                            tradeMethodList={tradeMethodList}
                            currency={data.currency}
                            brandCode={data.brandCode}
                            brandId={data.brandId}
                            dealerCode={data.dealerCode}
                            dealerId={data.dealerId}
                            selectKey={details.piDetailId}
                            onCancel={this.onCloseCBUSelectPanel}
                            onSelect={this.onSelectCBU} />
                    }
                    {
                        this.state.showProductPanel &&
                        <ProductPanel
                            selectKey={data.id}
                            brandId={data.brandId}
                            dealerId={data.dealerId}
                            onCancel={this.onCloseProductPanel}
                            onSelect={this.onSelectProduct} />
                    }
                    {
                        this.state.showPlanCodePanel &&
                        <PlanCodePanel
                            selectKey={details.productId}
                            brandId={data.brandId}
                            dealerId={data.dealerId}
                            materialGroupKDBOMCode={this.state.kdBomCode}
                            onCancel={this.onClosePlanCodePanel}
                            onSelect={this.onSelectPlanCode} />
                    }
                    {
                        this.state.showImportPanel &&
                        <ImportPanel
                            paymentType={data.paymentType}
                            salesOrderPriceTerms={data.salesOrderPriceTerms}
                            transportType={data.transportType}
                            tradeMethodId={data.tradeMethodId}
                            currency={data.currency}
                            brandId={data.brandId}
                            dealerId={data.dealerId}
                            selectKey={details.id}
                            onCancel={this.onCloseImportPanel}
                            onImportChange={this.onImportChange} />
                    }
                    {
                        this.state.showProductMutiPanel &&
                        <ProductMutiPanel
                            currentSelectRowkeys={details}
                            selectKey={details.productId}
                            brandId={data.brandId}
                            dealerId={data.dealerId}
                            onCancel={this.onCloseProductMutiPanel}
                            onSelect={this.onSelectProductMuti} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onSubmitForce: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onSubmit,
    onSubmitForce
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    initEnum: getinitEnumData(state),
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onSubmit(data, details)),
    onSubmitForce: (data, details) => dispatch(onSubmitForce(data, details)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
